<template>
  <section class="search">
    <input v-model="keyword" type="text" placeholder="请输入城市名或拼音">
    <div class="search-content" v-show="keyword" ref="search">
      <ul>
        <li class="search-item border-bottom"
        v-for="item in list"
        :key="item.id"
        @click="handleCityChange(item.name)">{{item.name}}</li>
        <li class="search-item border-bottom" v-show="noData">没有匹配的数据</li>
      </ul>
    </div>
  </section>
</template>

<script>
import BScroll from 'better-scroll'
import { mapMutations } from 'vuex'
export default{
  name: 'Search',
  data () {
    return {
      keyword: '',
      list: [],
      timer: null
    }
  },
  props: {
    cities: Object
  },
  computed: {
    noData () {
      return !this.list.length
    }
  },
  methods: {
    ...mapMutations(['CHANGE_CITY']),
    handleCityChange (city) {
      this.CHANGE_CITY(city)
      this.$router.push('/')
    }
  },
  mounted () {
    this.scroll = new BScroll(this.$refs.search)
  },
  watch: {
    keyword () {
      if (this.timer) {
        clearTimeout(this.timer)
      }
      if (!this.keyword) {
        this.list = []
        return
      }
      this.timer = setTimeout(() => {
        const res = []
        for (const i in this.cities) {
          this.cities[i].forEach(value => {
            if (value.name.indexOf(this.keyword) > -1 || value.spell.indexOf(this.keyword) > -1) {
              res.push(value)
            }
          })
        }
        this.list = res
      }, 100)
    }
  }
}
</script>

<style lang="stylus" scoped>
@import '~styles/variable.styl'
.search
  height .72rem
  padding 0 .1rem
  background-color $bgColor
  input
    width 100%
    height .62rem
    line-height .62rem
    text-align center
    border-radius .06rem
    color #666
    padding 0 .06rem
    box-sizing border-box
  .search-content
    overflow hidden
    z-index 1
    position absolute
    top 1.58rem
    right 0
    bottom 0
    left 0
    background-color #fff
    .search-item
      line-height .8rem
      padding 0 .1rem
</style>
